/*
 * @Author: jykl jykl@163.com
 * @Date: 2024-12-31 08:23:33
 * @LastEditors: jykl jykl@163.com
 * @LastEditTime: 2024-12-31 08:23:54
 * @FilePath: /react-management/src/views/InfiniteScroll/InfiniteScroll1.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useState, useEffect, useRef } from 'react'

// 模拟数据获取函数
const fetchMoreData = async (page) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const newData = Array.from(
        { length: 20 },
        (_, i) => `Item ${page * 20 + i + 1}`
      )
      resolve(newData)
    }, 1000)
  })
}

const InfiniteScroll = () => {
  const [data, setData] = useState([]) // 存储数据
  const [loading, setLoading] = useState(false) // 加载状态
  const [page, setPage] = useState(1) // 当前页面
  const containerRef = useRef(null) // 监听滚动的容器

  // 数据加载函数
  const loadMoreData = async () => {
    if (loading) return // 如果正在加载中，阻止重复加载

    setLoading(true)
    const newData = await fetchMoreData(page)
    setData((prevData) => [...prevData, ...newData]) // 追加数据
    setPage(page + 1) // 更新页面
    setLoading(false) // 设置加载状态为false
  }

  // 监听滚动事件
  const handleScroll = () => {
    const container = containerRef.current
    if (!container) return

    const { scrollTop, scrollHeight, clientHeight } = container

    // 如果滚动条接近底部，加载更多数据
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      loadMoreData()
    }
  }

  // 初始化加载更多数据
  useEffect(() => {
    loadMoreData() // 初始时加载第一批数据
  }, [])

  useEffect(() => {
    const container = containerRef.current
    if (container) {
      container.addEventListener('scroll', handleScroll) // 监听滚动事件
    }
    return () => {
      if (container) {
        container.removeEventListener('scroll', handleScroll) // 清理事件监听
      }
    }
  }, [loading])

  return (
    <div>
      <h1>下拉加载更多示例</h1>
      <div
        ref={containerRef}
        style={{ height: '400px', overflowY: 'auto', border: '1px solid #ccc' }}
      >
        <ul>
          {data.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
        {loading && <div>加载中...</div>}
      </div>
    </div>
  )
}

export default InfiniteScroll
